package com.seadragon.app.ksr.dao.jpa;

import java.util.List;

import javax.persistence.Query;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;

import com.seadragon.app.ksr.dao.StateDao;
import com.seadragon.app.ksr.model.tiger.State;

@Repository("StateDao")
@SuppressWarnings("unchecked")
public class StateDaoJpaImpl extends AbstractJpaDao implements StateDao {
	private static Logger logger = LoggerFactory.getLogger(StateDaoJpaImpl.class);
	
	@Override
	public List<State> findAdjacentStates(String stateName) {
		logger.info("Entering ... ");
		Query q = entityManager.createNamedQuery("findAdjacentStates").setParameter("stateName", stateName);
		q.setHint("org.hibernate.readOnly",true);
		logger.info("Leaving ...");
		return (List<State>)q.getResultList();
	}

	@Override
	public String findStatefpByStateName(String stateName) {
		CriteriaBuilder cb = entityManager.getCriteriaBuilder();
		CriteriaQuery<State> cq = cb.createQuery(State.class);
		Root<State> root = cq.from(State.class);
		cq.select(root);
		cq.where(cb.equal(root.get("stusps"), stateName));
		State state = entityManager.createQuery(cq).getSingleResult();
		return state.getStatefp();
	}

	@Override
	public void save(State state) {
		entityManager.persist(state);
	}
}
